package com.jp.knowledge.adapter;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class JPViewHolder {

    // http://blog.csdn.net/xyz_fly/article/details/7931943 二分法存储，按照键值从小到大排序
    private final SparseArray<View> mViews = new SparseArray<>();
    private View mConvertView;

    public JPViewHolder(Context context, int LayoutID, ViewGroup parent) {

        mConvertView = LayoutInflater.from(context).inflate(LayoutID, parent, false);
        mConvertView.setTag(this);
    }

    public static JPViewHolder get(Context context, int LayoutID, ViewGroup parent, View convertView) {
        if (convertView == null)
            return new JPViewHolder(context, LayoutID, parent);
        return (JPViewHolder) convertView.getTag();
    }

    public View getConvertView() {
        return mConvertView;
    }

    /**
     * @param viewId 控件ID
     * @param <T>    对象类型
     * @return 根据ID获取到的控件
     */
    public <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    /**
     * 这里仅以TextView为例，其他的可以更具需求再做衍生
     *
     * @param viewId 控件ID
     * @param str    设置文本内容
     */
    public void setText(int viewId, String str) {
        ((TextView) getView(viewId)).setText(str);
    }
}
